<template>
  <div class="playlist-container">
    <!-- 歌单分类标签区域 -->
    <div class="category-section">
      <!-- <h2 class="section-title">全部歌单</h2> -->
      <div class="category-tags">
        <el-tag
          v-for="category in displayedCategories"
          :key="category.id"
          :class="{ 'active-tag': activeCategory === category.code }"
          @click="selectCategory(category.code)"
        >
          {{ category.name }}
        </el-tag>
        <el-button
          v-if="categories.length > 8"
          class="more-button"
          @click="toggleShowAllCategories"
          size="small"
          type="text"
        >
          {{ showAllCategories ? "收起" : "更多" }}
        </el-button>
      </div>
    </div>

    <!-- 歌单展示区域 -->
    <div class="playlists-section">
      <div v-if="playlists.length === 0" class="empty-container">
        <div class="empty-icon">♪</div>
        <span>暂无歌单</span>
      </div>
      <div v-else class="playlist-grid">
        <div
          v-for="playlist in playlists"
          :key="playlist.playlistId"
          class="playlist-card"
          @click="viewPlaylistDetail(playlist.playlistId)"
        >
          <div class="cover-container">
            <el-image :src="playlist.coverUrl" class="cover-image" fit="cover">
              <template #error>
                <div class="cover-error">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </template>
            </el-image>
            <div class="play-count">
              <i class="el-icon-headset"></i>
              {{ formatCount(playlist.playCount) }}
            </div>
          </div>
          <div class="playlist-info">
            <h3 class="playlist-title">{{ playlist.playlistName }}</h3>
            <p class="playlist-description">
              {{ playlist.description || "暂无描述" }}
            </p>
            <div class="playlist-stats">
              <span class="songs-count">
                <i class="el-icon-service"></i> {{ playlist.songCount }}首
              </span>
              <span class="collect-count">
                <i class="el-icon-star-off"></i>
                {{ formatCount(playlist.collectCount) }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { ElMessage } from "element-plus";
import { defineComponent, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import api from "../services/api";

interface PlaylistCategory {
  id: number;
  name: string;
  code: string;
}

interface PlaylistItem {
  playlistId: number;
  playlistName: string;
  description?: string;
  coverUrl: string;
  creator: {
    userId: number;
    nickname: string;
  };
  songCount: number;
  playCount: number;
  collectCount: number;
  tags?: string[];
  createTime: string;
}

export default defineComponent({
  name: "PlayList",

  setup() {
    const activeCategory = ref<string>("all");
    const categories = ref<PlaylistCategory[]>([]);
    const displayedCategories = ref<PlaylistCategory[]>([]);
    const showAllCategories = ref<boolean>(false);
    const playlists = ref<PlaylistItem[]>([]);
    const router = useRouter();

    // 获取歌单分类标签
    const fetchCategories = async () => {
      try {
        const response = await api.httpClient.get("/playlists/tags");
        console.log("获取分类标签成功:", response.data);
        // 不再插入“全部”标签
        const tagList = response.data.map((tag: string, index: number) => ({
          id: index + 1,
          name: tag,
          code: tag.toLowerCase(),
        }));
        categories.value = tagList;
        activeCategory.value =
          categories.value.length > 0 ? categories.value[0].code : "";
        updateDisplayedCategories();
      } catch (error) {
        console.error("获取分类失败:", error);
        ElMessage.error("获取分类失败");
        // 如果 API 调用失败，使用默认分类（不插入“全部”标签）
        categories.value = [];
        activeCategory.value = "";
        updateDisplayedCategories();
      }
    };

    // 更新显示的分类标签
    const updateDisplayedCategories = () => {
      if (showAllCategories.value) {
        displayedCategories.value = categories.value;
      } else {
        displayedCategories.value = categories.value.slice(0, 8);
      }
    };

    // 切换显示全部分类标签
    const toggleShowAllCategories = () => {
      showAllCategories.value = !showAllCategories.value;
      updateDisplayedCategories();
    };

    // 根据标签获取歌单
    const fetchPlaylistsByTag = async (tagCode: string) => {
      try {
        // tagCode为空时查全部
        const params = {
          tag: tagCode || "",
          page: 1,
          size: 8,
        };
        const response = await api.playlistApi.getPlaylistsByTag(params);
        // 兼容后端返回结构
        const list = response.data.records || response.data.list || [];
        playlists.value = list;
      } catch (error) {
        console.error("获取歌单失败:", error);
        ElMessage.error("获取歌单失败");
        playlists.value = [];
      }
    };

    // 选择分类
    const selectCategory = (code: string) => {
      activeCategory.value = code;
      fetchPlaylistsByTag(code);
    };

    // 查看歌单详情
    // 跳转到歌单详情页
    const viewPlaylistDetail = (id: number) => {
      router.push({ name: "PlaylistDetail", params: { id } });
    };

    // 格式化大数字显示
    const formatCount = (count: number): string => {
      if (count >= 10000) {
        return (count / 10000).toFixed(1) + "万";
      }
      return count.toString();
    };

    onMounted(async () => {
      await fetchCategories();
      // 默认加载第一个分类歌单或全部（如果无分类）
      fetchPlaylistsByTag(activeCategory.value);
    });

    return {
      activeCategory,
      categories,
      displayedCategories,
      showAllCategories,
      playlists,
      selectCategory,
      toggleShowAllCategories,
      viewPlaylistDetail,
      formatCount,
    };
  },
});
</script>

<style scoped>
.playlist-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.section-title {
  font-size: 24px;
  color: #333;
  margin-bottom: 20px;
}

/* 标签居中显示并放大样式 */
.category-tags {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 30px;
}

.category-tags .el-tag {
  padding: 14px 24px;
  font-size: 18px;
  border-radius: 24px;
  transition: all 0.3s;
  border: 1px solid #dcdfe6;
  background-color: #f5f7fa;
  color: #606266;
}

.category-tags .el-tag:hover {
  background-color: #a588d8;
  color: white;
  border-color: #b37dc5;
}

.category-tags .el-tag:active {
  transform: scale(0.95);
}

.category-tags .active-tag {
  background-color: #cdacf5;
  color: white;
  border-color: #948fca;
}

.more-button {
  align-self: center;
  padding: 0 12px;
  font-size: 14px;
  color: #bf95dc;
  cursor: pointer;
  transition: color 0.3s;
}

.more-button:hover {
  color: #b480c1;
}

.playlist-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 25px;
}

.playlist-card {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s, box-shadow 0.3s;
  cursor: pointer;
}

.playlist-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.cover-container {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.cover-image {
  width: 100%;
  height: 100%;
  transition: transform 0.5s;
}

.playlist-card:hover .cover-image {
  transform: scale(1.05);
}

.cover-error {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  color: #909399;
  font-size: 40px;
}

.play-count {
  position: absolute;
  top: 10px;
  right: 10px;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 4px 8px;
  border-radius: 10px;
  font-size: 12px;
  display: flex;
  align-items: center;
}

.play-count i {
  margin-right: 4px;
}

.playlist-info {
  padding: 15px;
}

.playlist-title {
  font-size: 16px;
  font-weight: bold;
  margin: 0 0 8px 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.playlist-description {
  color: #606266;
  font-size: 13px;
  height: 40px;
  margin: 0 0 10px 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.playlist-stats {
  display: flex;
  justify-content: space-between;
  color: #909399;
  font-size: 12px;
}

.playlist-stats span {
  display: flex;
  align-items: center;
}

.playlist-stats i {
  margin-right: 4px;
}

.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
  color: #909399;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 12px;
  color: #c0c4cc;
}
</style>
